import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/main/logic.dart';
import 'package:yp/router.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/util.dart';

import 'state.dart';

class OrderDetialLogic extends GetxController {
  // final MainAppLogic MainAppLogics = Get.put(MainAppLogic());
  final MainLogic mainLogic = Get.put(MainLogic());

  final OrderDetialState state = OrderDetialState();

  void setSex(int sex) {
    state.sex = sex;
    update();
  }

  void selectStatus(int index) {
    if (index == 2) {
      Get.toNamed(RouteConfig.orderDeposit);
    }
    state.statusIndex = index;
    update();
  }

  @override
  void onInit() {
    super.onInit();

    // fluwx.weChatResponseEventHandler.listen((event) {
    //   if (event is fluwx.WeChatLaunchMiniProgramResponse) {
    //     /// 取消支付：extMsg:{"errMsg":"requestPayment:fail cancel","status":"30"}
    //     /// 支付成功 extMsg:{"errMsg":"requestPayment:ok","status":"20"}
    //     Map resultMap = json.decode(event.extMsg);
    //     if (resultMap != null) {
    //       if (resultMap["status"].toString() == "20") {
    //         toast("支付成功");
    //         setMoneyOver(SpUtil.getString('dingdan'), 1, 'Complete', 'success', 'a');
    //         // Get.toNamed(RouteConfig.orderComplete,
    //         //     arguments: {'dingdan': state.dingdan, 'shifu': state.shifu});
    //       } else {
    //         setMoneyOver(SpUtil.getString('dingdan'), 0, 'List', 'err', 'a');
    //         toast("支付失败");
    //         // Get.back(result: true);
    //       }
    //     } else {
    //       setMoneyOver(SpUtil.getString('dingdan'), 0, 'List', 'err', 'a');
    //       // Get.toNamed(RouteConfig.orderList, arguments: {'status': 0});
    //       // Get.back(result: true);
    //     }
    //   }
    // });

    state.id = Get.arguments['id'];
    state.status = Get.arguments['status'] ?? 1;
    state.ordertype = Get.arguments['ordertype'] ?? 1;
  }

  @override
  void onReady() {
    super.onReady();

    /// 获取订单详情
    var params = {
      'tml_num_id': state.id,
      'usr_num_id': SpUtil.getInt('empeNumId'),
      //'user_type': 1, user_type：以前传1网格，现在传2表示koc；
      'user_type': 2,
    };
    Api.orderDetail(params).listen((event) {
      state.userNum =
          int.parse(event['distribution_order_detail']['user_num_id']);
      state.detail = event['distribution_order_detail'];

      if (event['distribution_order_detail']['so_sign'] == 40 ||
          event['distribution_order_detail']['so_sign'] == 19) {
        /// 定金预售用这个接口补充
        getOrderDetail();
      }
      selfHelpAddress();
      if (state.detail["adr_num_id"] != null &&
          state.selfHelpAddressList.length > 0) {
        state.selfHelpAddressList.asMap().map((key, value) {
          if (value['sub_unit_num_id'].toString() ==
                  state.detail["adr_num_id"].toString() &&
              state.detail["adr_name"] != null) {
            state.selected = key;
            var item = state.selfHelpAddressList[key];
            state.dianAdr = item['prv_name'] +
                item['city_name'] +
                item['city_area_name'] +
                item['adr'];
            update();
          }
          return MapEntry(key, value);
        });
      }

      var tmp = event['distribution_order_detail']['item_lists'][0];

      print(">>>>>>>>>>>>$tmp");
      state.otherParams = {
        "title": tmp['distribution_order_item'][0]['item_name'],
        "sub_title":
            '单号：' + tmp['distribution_order_item'][0]['item_num_id'].toString(),
        "other_title_one": '',
        "img": tmp['distribution_order_item'][0]['item_picture'],
        "price": tmp['distribution_order_item'][0]['trade_amount'],
        "ec_shop_num_id": tmp['ec_shop_num_id'],
        "accessId": '23ee76b0-f8bd-11eb-8410-ddb6fa40e357', //默认总店
      };
      state.ec_shop_num_id = tmp['ec_shop_num_id'].toString();
      Api.getAccessID(tmp['ec_shop_num_id'].toString()).listen((event) {
        state.accessId = event["access_id"];
        update();
      });
      if (event['distribution_order_detail']['tml_type'] == 0) {
        state.tml_type = '立即发货';
      } else if (event['distribution_order_detail']['tml_type'] == 1) {
        state.tml_type = '预约发货';
        state.dateTime = DateTime.parse(
            event['distribution_order_detail']['ship_time_begin']);
      } else if (event['distribution_order_detail']['tml_type'] == 2) {
        state.tml_type = '暂不发货';
      }
      if (event['distribution_order_detail']['residue_time'] == null ||
          event['distribution_order_detail']['residue_time'] < 0) {
        state.timerValue == '';
      }
      int seconds =
          event['distribution_order_detail']['residue_time'] ~/ (1000);
      // int seconds =111111 ~/ (1000);
      state.timer = Timer.periodic(Duration(seconds: 1), (timer) {
        var d = Duration(seconds: seconds);
        List<String> parts = d.toString().split(':');
        state.timerValue = '${parts[0]}:${parts[1]}:${parts[2].split('.')[0]}';
        if (seconds == 0) {
          state.timer.cancel();
          if (state.detail['status_num_id'] == 1) {
            state.detail['order_state'] = 9;
            state.timerValue = '';
            state.detail['operate_status_name'] = '交易失败';
            update();
          }
          return;
        }

        seconds = --seconds;
        update();
      });
      if (event['distribution_order_detail']['residue_time'] == null ||
          event['distribution_order_detail']['residue_time'] < 0) {
        state.timerValue = '';
        state.timer.cancel();
      }
      if (event['distribution_order_detail']['adr_type'] == 1) {
        state.switchValue = true;
      }
      if (event['distribution_order_detail'].containsKey('tml_pay_infos') ==
          true) {
        print(
            "payMethods:${event['distribution_order_detail']['tml_pay_infos']}");
        List<String> payLists = [];
        state.payMethods = '';
        event['distribution_order_detail']['tml_pay_infos'].forEach((e) {
          var paytypename = e['pay_type_name'];
          if (payLists.contains(paytypename) == true) {
          } else {
            payLists.add(paytypename);
            state.payMethods = state.payMethods +
                (state.payMethods == '' ? '' : '+') +
                paytypename;
          }
        });
      }
      update();
    });

    // 查询个人购物卡
    var condition = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "card_status": 3, //购物卡状态 (1: 有效, 2:失效, 3: 可用)
      'access_token': SpUtil.getString('token'),
    };

    Api.walletInformation(condition).listen((event) {
      print('===========walletInformation==========');
      print(event);
      /*
      * {code: 0, message: 成功, full_message: null, available_cards: [],
      * invalid_cards: null, available_cards: [], valid_card_count: 0, total_card_count: 0,
      * invalid_card_count: null, total_available_amount: 0.0}
      *
      * */
      if (event['code'] == 0) {
        state.GiftcardList = event['available_cards'] ?? [];
        if (state.GiftcardList.length > 0) {
          for (var i = 0; i < state.GiftcardList.length; i++) {
            state.GiftcardList[i]['click'] = false;
          }
        }
      }
    });
  }

  /// 定金预售
  void getOrderDetail() {
    var params1 = {
      "use_platform": 2,
      'access_token': SpUtil.getString('token'),
      'parent_tml_num_id': state.id,
      'usr_num_id': SpUtil.getInt('empeNumId'),
    };

    Api.tkDetail(params1).listen((event) {
      if (event != null && event['code'] == 0) {
        state.detailOrderNumId = event['order_num_id'];
        state.detailDeliveryTime = event['delivery_time'];
        state.detailDuePayTime = event['due_pay_time'];
        state.balancePaymentDtme = event['balance_payment_dtme'];
        state.detail['due_pay_time'] = event['due_pay_time'];
        state.detailShopId = event['ec_shop_num_id'];
        update();
      }
    });
  }

  /// 修改地址
  void editAddress(Map<String, dynamic> add) {
    var params = {
      'access_token': SpUtil.getString('token'),
      'tml_num_id': state.id,
      'consumer_prv_num_id': add['prv_num_id'],
      'consumer_city_num_id': add['city_num_id'],
      'consumer_city_area_num_id': add['city_area_num_id'],
      'consumer_town_num_id': add['town_num_id'],
      'consumer_maplocation_x': add['maplocation_x'],
      'consumer_maplocation_y': add['maplocation_y'],
      'adr_num_id': add['adr_num_id'],
      'consumer_adr': add['adr'],
      'consumer_name': add['cont_empe'],
      'consumer_telephone': add['contact_no'],
      'adr_type': state.switchValue ? 1 : 0,
    };
    print("##############!###$params ---$add");

    Api.updateDetail(params).listen((event) {
      if (event['code'] == 0) {
        // toast("修改成功");
        update();
      }
    });
  }

  /// 选择配送方式
  void selectTranType(String value) {
    state.tran_type = value;
    update();
  }

  /// 选择配送类型
  void selectTmlType(String value) {
    state.tml_type = value;
    if (value == '立即发货') {
      var params = {
        'tml_num_id': state.id,
        'tml_type': 0,
        "usr_num_id": SpUtil.getInt('empeNumId'),
        'access_token': SpUtil.getString('token'),
      };
      Api.updateDetail(params).listen((event) {
        update();
      });
    } else if (value == '暂不发货') {
      var params = {
        'tml_num_id': state.id,
        'tml_type': 2,
        "usr_num_id": SpUtil.getInt('empeNumId'),
        'access_token': SpUtil.getString('token'),
      };
      Api.updateDetail(params).listen((event) {
        if (event['code'] == 0) {
          toast("修改成功");
        }
        update();
      });
    } else if (value == '预约发货') {
      print('时间');
      print((new DateTime.now().millisecondsSinceEpoch).toString());
      var params = {
        'tml_num_id': state.id,
        'tml_type': 1,
        "usr_num_id": SpUtil.getInt('empeNumId'),
        'ship_time_begin': (new DateTime.now()).toString(),
        'access_token': SpUtil.getString('token'),
      };
      Api.updateDetail(params).listen((event) {
        if (event['code'] == 0) {
          toast("修改成功");
        }
        update();
      });
    }
    update();
  }

  /// 拉起中金支付
  void startCPCNWeixinPay(String authCode) async {
    if (authCode.isEmpty) {
      toast("签名失败");
      return;
    }
    var result =
        await fluwx.payWithCPCN(appId: Config.WECHAT_APPID, authCode: authCode);

    // var result = fluwx.openWeChatApp();

    print("=========结果<<<$result>>>====");
  }

  void goToMoney(id) {
    print('回调错误1');
    var params1 = {
      'access_token': SpUtil.getString('token'),
      "out_trade_no": id,
      "plat_type": 7,
      "body": "jifen",
      "pay_way": 0,
      "use_platform": 2,
      'appid': Config.ZJ_APPID,
    };
    print('回调错误2');
    gotomoney(state, startCPCNWeixinPay, params1, id);
  }

  /// 是否自提点
  void switchType(bool value) {
    state.switchValue = value;
    if (value) {
      var params = {
        "prv_num_id": state.detail['consumer_prv_num_id'],
        "city_num_id": state.detail['consumer_city_num_id'],
        "city_area_num_id": state.detail['consumer_city_area_num_id'],
        "town_num_id": state.detail['consumer_town_num_id'],
        "maplocation_x": state.detail['consumer_maplocation_x'],
        "maplocation_y": state.detail['consumer_maplocation_y'],
        "adr_num_id": state.detail["adr_num_id"],

        "page": 1,
        "page_size": 10,
        "is_pick_up": 1
      };
      Api.selfHelpAddress(params).listen((event) {
        state.selfHelpAddressList = event['sub_unit_shop_list'];
        var data = event['sub_unit_shop_list'][0];
        state.detail['adr_name'] = data['sub_unit_name'];
        state.dianAdr = data['prv_name'] +
            data['city_name'] +
            data['city_area_name'] +
            data['adr'];
      });
    }
    if (state.selected == -1) return;
    var params = {
      'access_token': SpUtil.getString('token'),
      'tml_num_id': state.id,
      'consumer_prv_num_id': state.detail['consumer_prv_num_id'],
      'consumer_city_num_id': state.detail['consumer_city_num_id'],
      'consumer_city_area_num_id': state.detail['consumer_city_area_num_id'],
      'consumer_town_id': state.detail['consumer_town_num_id'],
      'consumer_maplocation_x': state.detail['consumer_maplocation_x'],
      'consumer_maplocation_y': state.detail['consumer_maplocation_y'],
      'adr_num_id': state.detail['adr_num_id'],
      'consumer_adr': state.detail['consumer_adr'],
      'consumer_name': state.detail['user_name'],
      'consumer_telephone': state.detail['consumer_telephone'],
      'adr_type': state.switchValue ? 1 : 0,
    };

    Api.updateDetail(params);
  }

  /// 选择时间
  void selectDate(DateTime value) {
    if (state.detail['so_sign'] == 14 && value.compareTo(state.dateTime) < 0) {
      String dueTime = state.dateTime.toString().split(' ')[0];
      toast('发货时间不能小于$dueTime');
      return;
    }
    state.dateTime = value;
    print('value');
    print(value);
    var time = '${DateFormat("yyyy-MM-dd hh:mm:ss").format(value)}';
    print(time);
    var tml_type = 0;
    if (state.tml_type == '立即发货') {
      tml_type = 0;
    } else if (state.tml_type == '预约发货') {
      tml_type = 1;
    } else if (state.tml_type == '暂不发货') {
      tml_type = 2;
    }
    var params = {
      'access_token': SpUtil.getString('token'),
      'tml_num_id': state.id,
      'ship_time_begin': time,
      'tml_type': tml_type,
      "usr_num_id": SpUtil.getInt('empeNumId')
    };
    Api.updateDetail(params).listen((event) {
      if (event['code'] == 0) {
        toast("修改成功");
      }
      update();
    });
    update();
  }

  void submit() {
    if (state.selected == -1) {
      toast("请选择自提点");
      return;
    }
    var params = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
      'tml_num_id': state.id,
      "consumer_prv_numId": state.a == 0
          ? state.selfHelpAddressList[state.selected]['prv_num_id']
          : state.a,
      "consumer_city_numId": state.b == 0
          ? state.selfHelpAddressList[state.selected]['city_num_id']
          : state.b,
      "consumer_city_area_num_id": state.c == 0
          ? state.selfHelpAddressList[state.selected]['city_area_num_id']
          : state.c,
      "consumer_town_num_id": state.d == 0
          ? state.selfHelpAddressList[state.selected]['town_num_id']
          : state.d,
      "consumer_maplocation_x": state.maplocationX == "0"
          ? state.selfHelpAddressList[state.selected]['maplocation_x']
          : state.maplocationX,
      "consumer_maplocation_y": state.maplocationY == "0"
          ? state.selfHelpAddressList[state.selected]['maplocation_y']
          : state.maplocationY,
      "adr_num_id": state.sub_unit_num_id == 0
          ? state.selfHelpAddressList[state.selected]['sub_unit_num_id']
          : state.sub_unit_num_id,
      'consumer_adr': state.adr == ""
          ? state.selfHelpAddressList[state.selected]['adr']
          : state.adr,
      'adr_type': 1,
      //"is_pick_up": 1,
    };

    // print("############>>>>>$params");return;
    Api.updateDetail(params).listen((event) {
      if (event['code'] == 0) {
        // toast("修改成功");
        onReady();
      }
      update();
    });
  }

  void selfHelpAddress() {
    var params = {
      "prv_num_id": state.detail['consumer_prv_num_id'],
      "city_num_id": state.detail['consumer_city_num_id'],
      "city_area_num_id": state.detail['consumer_city_area_num_id'],
      "town_num_id": state.detail['consumer_town_num_id'],
      "maplocation_x": state.detail['consumer_maplocation_x'],
      "maplocation_y": state.detail['consumer_maplocation_y'],
      "adr_num_id": state.detail["adr_num_id"],

      "page": 1,
      "page_size": 10,
      "is_pick_up": 1
    };
    Api.selfHelpAddress(params).listen((event) {
      state.selfHelpAddressList = event['sub_unit_shop_list'];

      if (state.detail != null &&
          state.detail["adr_num_id"] != null &&
          state.selfHelpAddressList.length > 0) {
        state.selfHelpAddressList.asMap().map((key, value) {
          if (value['sub_unit_num_id'].toString() ==
                  state.detail["adr_num_id"].toString() &&
              state.detail["adr_name"] != null) {
            state.selected = key;

            var item = state.selfHelpAddressList[key];
            state.dianAdr = item['prv_name'] +
                item['city_name'] +
                item['city_area_name'] +
                item['adr'];

            update();
          }
          return MapEntry(key, value);
        });
      }
      update();
    });
  }

  void selectDian(int i, item) {
    state.selected = i;
    state.a = item['prv_num_id'];
    state.b = item['city_num_id'];
    state.c = item['city_area_num_id'];
    state.d = item['town_num_id'];
    state.maplocationX = item['maplocation_x'];
    state.maplocationY = item['maplocation_y'];
    state.sub_unit_num_id = item['sub_unit_num_id'];
    state.adr = item['adr'];
    state.dianAdr = item['prv_name'] +
        item['city_name'] +
        item['city_area_name'] +
        item['adr'];

    update();
  }

  /// 取消订单
  void closeOrder(context) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('提示'),
            content: Text('是否关闭订单'),
            actions: <Widget>[
              FlatButton(
                onPressed: () => Navigator.of(context).pop(),
                child: Text('取消'),
              ),
              FlatButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  var params = {
                    'tml_num_id': state.id,
                    'usr_num_id': SpUtil.getInt('empeNumId'),
                  };
                  Api.closeOrder(params).listen((event) {
                    if (event['code'] == 0) {
                      toast("操作成功");
                      Get.back(result: true);
                    } else {
                      toast(event["message"]);
                    }
                    update();
                  });
                },
                textColor: Colors.red,
                child: Text('确定'),
              ),
            ],
          );
        });
  }

  // 确认收货
  void confirmRec(data) {
    /// 获取订单详情
    var params = {
      'access_token': SpUtil.getString('token'),
      'tml_num_id': data['tml_num_id'],
      'usr_num_id': SpUtil.getInt('empeNumId'),
    };

    Api.confirmReceived(params).listen((event) {
      if (event['code'] == 0) {
        toast('确认收货成功');
        Get.back();
      } else {
        toast(event['message']);
      }
    });
  }

  // 添加购物车
  void buyAgain(Map orderitem) {
    var params = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "emp_num_id": 0,
      "channel_num_id": 99,
      "quantity": 1.0,
      "ec_shop_num_id": orderitem['ec_shop_num_id'],
      "item_num_id": orderitem['item_num_id'],
      "style_num_id": orderitem['style_num_id'],
      "ec_style_num_id": orderitem['style_num_id'],
      'access_token': SpUtil.getString('token'),
    };
    Api.addShoppingCart(params).listen((event) {
      if (event['code'] == 0) {
        // MainAppLogics.getCartNum();

        toast('添加成功');
      } else {
        toast('添加失败');
      }
    });
  }

  void setGift(index) {
    print(state.isGiftMoney);
    setcard(state, index);
    update();
  }

  // 计算选择的卡金额
  calculateCardAmount() {
    var amt = 0.0;
    if (state.GiftcardList.length == 0) {
      return amt;
    }
    for (var i = 0; i < state.GiftcardList.length; i++) {
      if (state.GiftcardList[i]['click']) {
        amt = amt + state.GiftcardList[i]['money_available'];
      }
    }
    return amt;
  }

  // 拼接区域文本
  String fmtRegion() {
    String result = '';
    result = state.detail['consumer_prv_name'] +
        '/' +
        state.detail['consumer_city_name'] +
        '/' +
        state.detail['consumer_city_area_name'];
    return result;
  }

  /// 退预售定金
  void refund({info}) {
    var params = {
      "channel_num_id": 99,
      "use_platform": 2,
      "evidence_list": [],
      "items": [
        {
          "item_num_id": info['distribution_order_item'][0]['item_num_id'],
          "qty": info['distribution_order_item'][0]['qty'],
          "price": info['distribution_order_item'][0]['trade_price'],
          "pmt_sign": info['distribution_order_item'][0]['pmt_sign'],
          "tml_line": info['distribution_order_item'][0]['series']
        }
      ],
      "remark": 1,
      "return_type": 1,
      "source_tml_num_id": info['tml_num_id'],
      // "source_tml_num_id": state.detailOrderNumId,
      "access_token": SpUtil.getString('token'),
      "all_refund": 1,
      "return_way": 1,
      "goodsReturn_flag": 0
    };
    Api.tkApply(params).listen((event) {
      if (event['code'] == 0) {
        toast(event['message']);
        Navigator.pop(Get.context);
        Get.toNamed(RouteConfig.applySuccess,
            arguments: {'back_tml_num_id': event['back_tml_num_id']});
      } else {
        toast(event['message']);
      }
      update();
    });
  }
}
